package com.softbank.hwbanner;

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import java.util.ArrayList;
import java.util.List;

public class HWBanner extends FrameLayout implements IIndicator {

    private IIndicator mIndicator;
    private View indicatorView;
    //指示器默认的高度（单位dp）
    private int mDefaultIndicatorHeight = 20;


    private ViewPager mViewPager;

    /**
     * 宽高比例，默认是16/9
     */
    private double mRadio = 32 / 15;

    private int mSize;
    private int mOffset;
    private double mPercent;
    private int mPrimateOffset;

    List<View> bottomViewList = new ArrayList<>();//将要分页显示的View装入数组中
    List<View> topViewList = new ArrayList<>();//将要分页显示的View装入数组中

    /**
     * 装载每一个底部或顶部View
     */
    private List<ItemViewGroup> itemViewGroups;
    private int mDefaultViewPagerPadding = 10;


    public HWBanner(@NonNull Context context) {
        super(context);
        init();
    }

    public HWBanner(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setWillNotDraw(false);
        initViewPager();
    }

    private void initViewPager() {
        //设置ViewPager铺满整个View
        mViewPager = new ViewPager(getContext());
        addView(mViewPager);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            private int mCurrentIndex = 0;

            /**
             * @param visibleIndex 从左到右第一个可见的索引
             * @param percent 百分比
             * @param i1 偏移像素
             */
            @Override
            public void onPageScrolled(int visibleIndex, float percent, int i1) {
                mIndicator.setOffset(visibleIndex, percent);
                View view;
                if (visibleIndex == mCurrentIndex) {
                    //当前位置相对正常位置向左偏移了（即总体趋势是向左边滑动，右边下一个出现了一部分）

                    if (mCurrentIndex + 1 < topViewList.size()) {
                        view = topViewList.get(mCurrentIndex + 1);
                        view.setX((int) ((1 - percent) * mPrimateOffset));
                    }
                    view = topViewList.get(mCurrentIndex);
                    view.setX((int) ((-percent) * mPrimateOffset));
                } else {
                    //当前位置相对正常位置向右偏移了（即总体趋势是向右边滑动，上一个在左边出现了一部分）
                    if (mCurrentIndex - 1 >= 0) {
                        view = topViewList.get(mCurrentIndex - 1);
                        view.setX((int) ((-percent) * mPrimateOffset));
                    }
                    view = topViewList.get(mCurrentIndex);
                    view.setX((int) ((1 - percent) * mPrimateOffset));
                }
            }

            @Override
            public void onPageSelected(int i) {
                mIndicator.setCurrentItem(i);
                mCurrentIndex = i;
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    public void setIndicatorView(View view) {
        if (view instanceof IIndicator) {
            if (mIndicator != null) {
                for (int i = 0; i < getChildCount(); i++) {
                    View childView = getChildAt(i);
                    if (childView instanceof IIndicator) {
                        removeView(childView);
                        break;
                    }
                }
            }
            mIndicator = (IIndicator) view;
            indicatorView = view;
            addView(indicatorView);
            if (itemViewGroups != null && itemViewGroups.size() > 0) {
                mIndicator.setSize(itemViewGroups.size());
            } else {
                mIndicator.setSize(1);
            }
        }
    }

    public IIndicator getIndicator() {
        return mIndicator;
    }

    public void setItemViewGroups(List<ItemViewGroup> itemViewGroups) {
        List<View> views = new ArrayList<>();
        if (!topViewList.isEmpty()) {
            for (int i = 0; i < getChildCount(); i++) {
                if (topViewList.contains(getChildAt(i))) {
                    views.add(getChildAt(i));
                }
            }
            for (View view : views) {
                removeView(view);
            }
            bottomViewList.clear();
            topViewList.clear();
        }

        this.itemViewGroups = itemViewGroups;
        for (ItemViewGroup itemViewGroup : itemViewGroups) {
            bottomViewList.add(itemViewGroup.getBottomView());
            topViewList.add(itemViewGroup.getTopView());
            addView(itemViewGroup.getTopView());
        }
        if (mIndicator != null) {
            mIndicator.setSize(itemViewGroups.size());
        }
        mPagerAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        boolean isFirstTopChild = true;
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            if (topViewList.contains(view)) {
                //铺满
                if (isFirstTopChild) {
                    view.layout(0, 0, 0 + getMeasuredWidth(), getMeasuredHeight());
                    isFirstTopChild = false;
                } else {
                    view.layout(mPrimateOffset, 0, mPrimateOffset + getMeasuredWidth(), getMeasuredHeight());
                }
            }
        }

        if (indicatorView != null) {
            double density = getResources().getDisplayMetrics().density;
            int height = (int) (density * mDefaultIndicatorHeight);
            indicatorView.layout(0, getMeasuredHeight() - height,
                    getMeasuredWidth(), getMeasuredHeight());
            Log.e("test6", indicatorView.getMeasuredHeight() + "");
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        super.onMeasure(MeasureSpec.makeMeasureSpec(width,
                MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
                (int) (width / mRadio), MeasureSpec.EXACTLY));
        //初始化初始偏移量
        mPrimateOffset = (int) (getMeasuredWidth() * 1.6);

        LayoutParams layoutParams = new LayoutParams(getMeasuredWidth(), getMeasuredHeight());
        if (mViewPager == null) {
            //铺满
            mViewPager.setLayoutParams(layoutParams);
            mViewPager.measure(widthMeasureSpec, heightMeasureSpec);
        }

        //同样也是铺满整个view
        for (View view : topViewList) {
            view.setLayoutParams(layoutParams);
            view.measure(widthMeasureSpec, heightMeasureSpec);
        }

        //设置指示器的宽高
        if (indicatorView != null) {
            double density = getResources().getDisplayMetrics().density;
            layoutParams = new LayoutParams(getMeasuredWidth(), (int) (density * mDefaultIndicatorHeight));
            indicatorView.setLayoutParams(layoutParams);
        }
    }

    @Override
    public void setSize(int size) {
        mSize = size;
    }

    @Override
    public int getSize() {
        return mSize;
    }

    @Override
    public void setCurrentItem(int current) {
//        mCurrentItem = current;
    }

    @Override
    public void setOffset(int visibleIndex, double percent) {
        mPercent = percent;
    }

    private PagerAdapter mPagerAdapter = new PagerAdapter() {
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return bottomViewList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            container.removeView(bottomViewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(bottomViewList.get(position));
            return bottomViewList.get(position);
        }
    };

    public static class ItemViewGroup {
        /**
         * 顶部和底部view
         */
        private View bottomView, topView;
        private int layoutId;
        private Context context;

        public ItemViewGroup(View bottomView, View topView) {
            this.bottomView = bottomView;
            this.topView = topView;
            this.context = topView.getContext();
            this.layoutId = 0;
        }

        /**
         * 通过一个xml文件来创建ViewGroup
         */
        public ItemViewGroup(Context context, int layoutId) {
            this.layoutId = layoutId;
            this.context = context;
            ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this.context).inflate(layoutId, null);
            if (viewGroup.getChildCount() < 2) {
                throw new IllegalArgumentException("The view group that inflated by the given resource id should contain at least 2 child view.");
            }
            bottomView = viewGroup.getChildAt(0);
            topView = viewGroup.getChildAt(1);
            viewGroup.removeAllViews();
        }

        public View getBottomView() {
            return bottomView;
        }

        public View getTopView() {
            return topView;
        }
    }
}
